package net.wofly.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import net.wofly.common.util.LoggerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogInterceptor implements HandlerInterceptor {
    
    //请求开始时间标识
    private static final String LOGGER_SEND_TIME = "_send_time";
    Logger log = LoggerFactory.getLogger(this.getClass());
    
    /**
     * 进入SpringMVC的Controller之前开始记录日志实体
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //获取请求sessionId
        log.info(">>> sessionId:" + request.getRequestedSessionId());
        //客户端ip
        log.info(">>> 客户端ip：" +LoggerUtil.getCliectIp(request));
        //请求路径
        log.info(">>> url:" + request.getRequestURI());
        //请求方法
        log.info(">>> 请求方法：" +request.getMethod());
        //获取请求参数信息 内容json字符串
        log.info(">>> 请求参数：" + JSON.toJSONString(request.getParameterMap(),
                SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue));
 
        //请求类型（json|普通请求）
        log.info(">>> 请求类型：" +LoggerUtil.getRequestType(request));
        //请求开始时间
        request.setAttribute(LOGGER_SEND_TIME, System.currentTimeMillis());
        return true;
    }
    
    @Override
    public void postHandle(
            HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
            ModelAndView modelAndView) throws Exception {
        
    }
    
    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        //请求错误码
        log.info(">>> response status:" + response.getStatus());
        //当前时间
        long currentTime = System.currentTimeMillis();
        //请求开始时间
        long time = Long.valueOf(request.getAttribute(LOGGER_SEND_TIME).toString());
        //请求时间差
        log.info(">>> 请求耗时：" + ((currentTime - time) + ""));
        //设置返回值
        log.info(">>> 返回数据：" + JSON.toJSONString(request.getAttribute(LoggerUtil.LOGGER_RETURN),
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue));
    }
    
    /**
     * 根据传入的类型获取spring管理的对应Bean
     *
     * @param clazz   类型
     * @param request 请求对象
     * @param <T>
     * @return
     */
    private <T> T getBean(Class<T> clazz, HttpServletRequest request) {
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        return factory.getBean(clazz);
    }
}
